package com.idbk.chargestation.service;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Vibrator;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;

import com.idbk.chargestation.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * service后台下载更新包
 * @author zhx
 *
 */
public class UpdateService extends Service{

	private final static int MSG_DOWNLOAD_FINISH = 30000;

	private final static int MSG_DOWNLOAD_PROGRESS = 30001;

	// 下载应用存放全路径  
	private static final String FILE_NAME = "ChargeStation.apk"; 
	//进度条的当前刻度值  
	private int curProgress = 0;
	//用户是否取消下载  
	private boolean isCancel = false; 
	private String mApkUrl;
	private NotificationManager mNotificationManager = null;  
	private NotificationCompat.Builder builder; 
	private static final int NOTIFICATION_ID = 124;

	 @Override  
     public void onCreate() { 
          super.onCreate();  
     }  
	 
	 @Override
		public IBinder onBind(Intent intent) {
			return null;
		}

     @Override  
     public int onStartCommand(Intent intent, int flags, int startId) { 
         // 接收Intent传来的参数:  
         mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
         builder = new NotificationCompat.Builder(getApplicationContext());  
         builder.setSmallIcon(R.drawable.ico_login_logo);
         builder.setProgress(100, 0, false);
         builder.setNumber(0);  
         builder.setAutoCancel(true);
         if (intent == null) {
             builder.setContentTitle("下载失败");  
             builder.setContentText(getString(R.string.load_failed_try_agin));
             stopSelf();
             
         } else {
        	 builder.setTicker(getString(R.string.load_new_app));
             builder.setContentTitle(getString(R.string.loading_app));
             builder.setContentText(getString(R.string.loading_app_please_waitting));
             if (intent.getStringExtra("apk_url") != null) {
            	 mApkUrl = intent.getStringExtra("apk_url");
             } 
             downloadApp(mApkUrl);
		}
         mNotificationManager.notify(NOTIFICATION_ID, builder.build());   

        return super.onStartCommand(intent, flags, startId);  
     }  


 	
 	private void downloadApp(final String destUrl) {  
 		new Thread(new Runnable() {  
 			@Override  
 			public void run() {  
 				URL url;
 				InputStream in = null;  
 				FileOutputStream out = null;  
 				HttpURLConnection conn = null;  
 				int progress = 0;
 				try {  
 					url = new URL(destUrl);  
 					conn = (HttpURLConnection) url.openConnection();  
 					conn.setConnectTimeout(5000);
 					conn.connect();  
 					long fileLength = conn.getContentLength();  
 					in = conn.getInputStream();
 					
 					File file = new File(
 							getApplicationContext().getExternalFilesDir(null),
 							FILE_NAME);  
 					if(file.exists()){
 						file.delete();
 					}
 					out = new FileOutputStream(file);  
 					byte[] buffer = new byte[1024];  
 					int len;
 					long readLength = 0L;
 					while((len = in.read(buffer)) != -1) {  
 						// 用户点击“取消”按钮，下载中断  
 						if(isCancel) {  
 							break;  
 						}  
 						out.write(buffer, 0, len);  
 						readLength += len;
 						if (curProgress != 0) {
 							progress = curProgress;
 						}
 						curProgress = (int) (((float) readLength / fileLength) * 100);
 						if (curProgress <= 100 && (curProgress > progress)) {
 							handler.sendEmptyMessage(MSG_DOWNLOAD_PROGRESS); 
 						}
 						if(readLength >= fileLength) {
 							// 下载完毕，通知安装  
 							handler.sendEmptyMessage(MSG_DOWNLOAD_FINISH);  
 							break;  
 						}  
 					}  
 					out.flush();  
 				} catch (Exception e) {  
 					e.printStackTrace();  
 				} finally {  
 					if(out != null) {  
 						try {  
 							out.close();  
 						} catch (IOException e) {  
 							e.printStackTrace();  
 						}  
 					}  
 					if(in != null) {  
 						try {  
 							in.close();  
 						} catch (IOException e) {  
 							e.printStackTrace();  
 						}  
 					}  
 					if(conn != null) {  
 						conn.disconnect();  
 					}  
 				}  
 			}  
 		}).start();  
 	}  

 	private final Handler handler = new Handler(){  
 		@Override  
 		public void handleMessage(Message msg) {  
 			switch (msg.what) {  
 			case MSG_DOWNLOAD_PROGRESS:  
				builder.setContentText("正在下载,已下载" + curProgress + "%");
 				builder.setProgress(100, curProgress, false);
				mNotificationManager.notify(NOTIFICATION_ID, builder.build()); 
 				break; 	  
 			case MSG_DOWNLOAD_FINISH:
 				File file = new File(
 						getApplicationContext().getExternalFilesDir(null),
 						FILE_NAME);
 				if (!file.exists()) {
 					Toast.makeText(getApplicationContext(), "文件不存在，无法安装", Toast.LENGTH_SHORT).show();
 					return;
 				}
 				Intent intent = new Intent();  
 		 		intent.setAction(Intent.ACTION_VIEW);  
 		 		intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); 
 		 		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 		 		PendingIntent mPendingIntent = PendingIntent.getActivity(UpdateService.this, 0, intent, 0);
 		 		
	 			builder.setContentTitle("下载完成");
 				builder.setProgress(100, 100, false);
 				builder.setContentText("下载完成,已下载100%");
 				builder.setContentIntent(mPendingIntent);
				mNotificationManager.notify(NOTIFICATION_ID, builder.build()); 
 				Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);  
                vibrator.vibrate(100L);// 参数是震动时间(long类型)
                
 				stopSelf();
 		 		startActivity(intent);  
 				break;
			default:
				break;
 			}  
 		}  
 	};  
 	
 	

}
